package com.archstoday.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.adapter.CommentForTopicAdapter;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.CommentCommitEntity;
import com.archstoday.entity.SchemeDetailEntity;
import com.archstoday.entity.TopicDetailComentEntity;
import com.archstoday.event.MessageRefreshSchemeDetailEvent;
import com.archstoday.event.MessageRefreshSchemeEvent;
import com.archstoday.utils.KeybordUtil;
import com.archstoday.utils.OAuthUtils;
import com.archstoday.utils.ToolUtils;
import com.archstoday.view.PullToRefreshLayout;
import com.base.http.common.BaseHttpClient;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;
import com.gifdialog.DialogUtil;
import com.gifdialog.GifDialog;
import com.xw.repo.refresh.PullListView;

import org.greenrobot.eventbus.EventBus;

public class SpecialCommentActivity extends AsScrollBaseActivity implements PullToRefreshLayout.OnRefreshListener, CommentForTopicAdapter.onReplyListener {
    private TextView mTitleTv;
    private LinearLayout mNoneLayout;

    //评论信息
    private PullToRefreshLayout mPullLayout;
    private PullListView mPullList;

    private CommentForTopicAdapter mCommentForTopicAdapter;
    private int page;
    private GifDialog loadingDialog;

    private TextView mCommitTv;

    private int mArticleId, mCategoryId1;
//    SchemeDetailEntity mSchemeDetailEntity;
    TopicDetailComentEntity mTopicDetailComentEntity;

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_special_comment);

        mNoneLayout = (LinearLayout) findViewById(R.id.search_none_layout);

        mTitleTv = (TextView) findViewById(R.id.title_tv);
        mCommitTv = (TextView) findViewById(R.id.id_for_topic_detail_comment);

        mPullLayout = (PullToRefreshLayout) findViewById(R.id.pull_layout);
        mPullList = (PullListView) findViewById(R.id.pull_list);
        mPullLayout.setOnRefreshListener(this);
    }

    @Override
    protected void initData(Bundle bundle) {
//        mSchemeDetailEntity = (SchemeDetailEntity) getIntent().getSerializableExtra("data");

        mArticleId = getIntent().getIntExtra("articleId", 0);
        mCategoryId1 = getIntent().getIntExtra("categoryId1", 0);

        mTitleTv.setText("评论");

        mCommentForTopicAdapter = new CommentForTopicAdapter(mContext);
        mCommentForTopicAdapter.setListener(this);
        mPullList.setAdapter(mCommentForTopicAdapter);
        mCommentForTopicAdapter.notifyDataSetChanged();

        page = 1;

        getCommentData();
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.back_btn);
        setOnClickListener(R.id.id_for_topic_detail_comment);

        mPullList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("onItemClick", "onItemClick");

                commitatPerson = mCommentForTopicAdapter.getItem(position);

                show(null, commitatPerson);
            }
        });
    }

    @Override
    public void reply(TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel data, TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel.RepliesModel info) {
        commitatPerson = data;

        show(info, data);
    }

    TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel commitatPerson;

    @Override
    public void treatClickEvent(int id) {
        switch (id) {
            case R.id.back_btn:
                appFinish();
                break;

            case R.id.id_for_topic_detail_comment:
                show(null, commitatPerson);
                break;
        }
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        mPullLayout.refreshFinish(true);
        mPullLayout.loadMoreFinish(true);

        if (client.getUrlIdentifier() == AsRes.TOPIC_DETAIL_COMMENT) {
            mTopicDetailComentEntity = (TopicDetailComentEntity) parse;

            if (ToolUtils.isSuccess(mTopicDetailComentEntity.getStatus())) {
                if (mTopicDetailComentEntity.getData() == null) {
                    return;
                }

                TopicDetailComentEntity.DataModelXX.CommentsModel entity = mTopicDetailComentEntity.getData().getComments();

                if (entity.getData() != null && entity.getData().size() > 0) {
                    mNoneLayout.setVisibility(View.GONE);

                    if (page == 1) {
                        mCommentForTopicAdapter.setData(entity.getData());
                    } else {
                        mCommentForTopicAdapter.addData(entity.getData());
                    }
                    page++;
                } else {

                    if (page == 1) {
                        mNoneLayout.setVisibility(View.VISIBLE);
                    } else {
                        mPullList.setPullUpEnable(false);
                    }
                }
            } else if (mTopicDetailComentEntity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            }

            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
        } else if (client.getUrlIdentifier() == AsRes.TOPIC_COMMIT_COMMENT) {
            CommentCommitEntity mCommentCommitEntity = (CommentCommitEntity) parse;

            if (ToolUtils.isSuccess(mCommentCommitEntity.getStatus())) {
                Toast.makeText(mContext, "发布成功~~~", Toast.LENGTH_SHORT).show();

                //刷新方案列表
                EventBus.getDefault().post(new MessageRefreshSchemeEvent());
                EventBus.getDefault().post(new MessageRefreshSchemeDetailEvent());

                //刷新评论列表
                //只有成功后 才进行评论的加载
                page = 1;
                getCommentData();
            } else if (mCommentCommitEntity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            } else {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }

                Toast.makeText(mContext, mCommentCommitEntity.getMsg(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void getCommentData() {
//        if (mSchemeDetailEntity == null) {
//            return;
//        }

        initParameter();

//        SchemeDetailEntity.DataModel dataBean = mSchemeDetailEntity.getData();

        mParams.put("articleId", mArticleId); //dataBean.getArticleId());
        mParams.put("categoryId1", mCategoryId1); //dataBean.getCategoryId1());
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", BaseApp.getDeviceID(mContext));
        mParams.put("page", page);
        mParams.put("pageSize", 10);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.TOPIC_DETAIL_COMMENT),
                AsRes.TOPIC_DETAIL_COMMENT, mParams, TopicDetailComentEntity.class);
    }

    private void show(final TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel.RepliesModel repliesModel, final TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel cap) {
        //设置固定的dialog
        final Dialog bottomDialog = new Dialog(mContext, R.style.BottomDialog);

        View contentView = LayoutInflater.from(mContext).inflate(R.layout.item_for_comment, null);
        bottomDialog.setContentView(contentView);

        final EditText tvContent = (EditText) contentView.findViewById(R.id.id_for_commit_content);
        displayplay(tvContent, repliesModel, cap);

        final TextView tvCancel = (TextView) contentView.findViewById(R.id.id_for_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //开启键盘，修复无法点击的Bug
                if (KeybordUtil.isSoftInputShow(SpecialCommentActivity.this)) {
                    KeybordUtil.closeKeybord(tvContent, mContext);
                }

                bottomDialog.dismiss();
            }
        });

        TextView tvCommit = (TextView) contentView.findViewById(R.id.id_for_commit);
        tvCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
                    showToast(R.string.user_userid_null);

                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                    appFinish();
                    return;
                }

                //开启键盘，修复无法点击的Bug
                if (KeybordUtil.isSoftInputShow(SpecialCommentActivity.this)) {
                    KeybordUtil.closeKeybord(tvContent, mContext);
                }

                bottomDialog.dismiss();

                //发表评论
                commitComment(tvContent, cap, repliesModel);
            }
        });


        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.setCancelable(true);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                KeybordUtil.closeKeybord(tvContent, mContext);
                bottomDialog.dismiss();
            }
        });
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();

        //开启键盘，修复无法点击的Bug
        KeybordUtil.openKeybord(tvContent, mContext);
    }

    private void displayplay(EditText tvContent, TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel.RepliesModel repliesModel, TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel cap) {
        if (repliesModel != null) {
            tvContent.setText("@" + repliesModel.getUserName() + " ");
            tvContent.setSelection(tvContent.getText().toString().length());
            return;
        }

        if (cap != null) {
            tvContent.setText("@" + cap.getComment().getUserName() + " ");
            tvContent.setSelection(tvContent.getText().toString().length());
            return;
        }
    }

    private void commitComment(EditText content, TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel cp, TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel.RepliesModel repliesModel) {

//        if (mSchemeDetailEntity == null) {
//            return;
//        }

        loadingDialog = new DialogUtil().showGifdialog(mContext);
        loadingDialog.show();

        String type = cp == null ? "1" : "2";
        String c = content.getText().toString().trim();

        initParameter();
        mParams.put("type", type);

        if ("1".equalsIgnoreCase(type)) {
            mParams.put("articleId", mArticleId);//mSchemeDetailEntity.getData().getArticleId());//文章ID，主评论(type=1)时必填
            mParams.put("categoryId1", mCategoryId1);//mSchemeDetailEntity.getData().getCategoryId1());//一级类目Id，主评论(type=1)时必填
        }

        if ("2".equalsIgnoreCase(type)) {
            if (repliesModel == null) {
                mParams.put("rootCommentId", commitatPerson.getComment().getCommentId());//回复的主评论Id，回复评论(type=2)时必填
                mParams.put("userIdReplied", commitatPerson.getComment().getUserId());//回复的评论的用户Id，回复评论(type=2)时必填

                c = c.replace("@" + commitatPerson.getComment().getUserName() + " ", "");
            } else {
                mParams.put("rootCommentId", repliesModel.getRootCommentId());//回复的主评论Id，回复评论(type=2)时必填
                mParams.put("userIdReplied", repliesModel.getUserId());//回复的评论的用户Id，回复评论(type=2)时必填

                c = c.replace("@" + repliesModel.getUserName() + " ", "");
            }
        }

        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", BaseApp.getDeviceID(mContext));
        mParams.put("commentText", c);

        //清空输入框
        content.setText("");
        mCommitTv.setText("");
        commitatPerson = null;

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.TOPIC_COMMIT_COMMENT),
                AsRes.TOPIC_COMMIT_COMMENT, mParams, CommentCommitEntity.class);
    }

    @Override
    protected void onError(Throwable error, BaseHttpClient client) {
        new Thread() {
            @Override
            public void run() {
                new Handler(Looper.getMainLooper()).post(runnable);
            }
        }.start();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mPullLayout.refreshFinish(true);
            mPullLayout.loadMoreFinish(true);

            if (mCommentForTopicAdapter.getCount() == 0) {
                mPullList.setPullUpEnable(false);
            }

            showToast(R.string.intent_error);
        }
    };


    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        //只有成功后 才进行评论的加载
        page = 1;
        getCommentData();
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        getCommentData();
    }


}
